package eft.android.view;

import java.util.ArrayList;
import java.util.Calendar;

import me.croute.calendarexample.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import eft.android.controller.Controller;
import eft.android.model.CrossfitDataManage;



/*
 * 
 * 
 */
public class CalendarViewActivity extends Activity implements OnItemClickListener, OnClickListener
{
	public static int SUNDAY 		= 1;
	public static int MONDAY 		= 2;
	public static int TUESDAY 		= 3;
	public static int WEDNSESDAY 	= 4;
	public static int THURSDAY 		= 5;
	public static int FRIDAY 		= 6;
	public static int SATURDAY 		= 7;
	public static int dayOfToday = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
	public static int monthOfToday = Calendar.getInstance().get(Calendar.MONTH);
	public static int yearOfToday = Calendar.getInstance().get(Calendar.YEAR);

	
	private TextView mTvCalendarTitle;
	private GridView mGvCalendar;

	private ArrayList<DayInfo> mDayList;
	private CalendarAdapter mCalendarAdapter;
	
	private Controller controller;

	private String packageName;

	Calendar mLastMonthCalendar;
	Calendar mThisMonthCalendar;
	Calendar mNextMonthCalendar;
	String [] dayText = {"SUN","MON","TUE","WED","THU","FRI","SAT"};

	CalendarViewActivity autoInstance;

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calendarviewactivity);

		autoInstance = this;
		packageName = this.getPackageName();
		controller = Controller.getInstance();

		Button bLastMonth = (Button) findViewById(R.id.gv_calendar_activity_b_last);
		Button bNextMonth = (Button) findViewById(R.id.gv_calendar_activity_b_next);
		Button bReturn = (Button)findViewById(R.id.gv_calendar_activity_return);
		Button bHistory = (Button)findViewById(R.id.gv_calendar_activity_history);
		Drawable alpha1 = bLastMonth.getBackground();
		alpha1.setAlpha(0);
		Drawable alpha2 = bNextMonth.getBackground();
		alpha2.setAlpha(0);
		Drawable alpha3 = bReturn.getBackground();
		alpha3.setAlpha(0);
		Drawable alpha4 = bHistory.getBackground();
		alpha4.setAlpha(0);

		mTvCalendarTitle = (TextView) findViewById(R.id.gv_calendar_activity_tv_title);
		mGvCalendar = (GridView) findViewById(R.id.gv_calendar_activity_gv_calendar);

		bLastMonth.setOnClickListener(this);
		bNextMonth.setOnClickListener(this);
		bReturn.setOnClickListener(this);
		bHistory.setOnClickListener(this);
		mGvCalendar.setOnItemClickListener(this);

		mDayList = new ArrayList<DayInfo>();
		
		CrossfitDataManage dataCreate = new CrossfitDataManage(this);
		dataCreate.close();
		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume()
	{
		super.onResume();

		mThisMonthCalendar = Calendar.getInstance();
		mThisMonthCalendar.set(Calendar.DAY_OF_MONTH, 1);
		getCalendar(mThisMonthCalendar);
	}

	/**
	 * 
	 * @param calendar 
	 */
	private void getCalendar(Calendar calendar)
	{
		int lastMonthStartDay;
		int dayOfMonth;
		int thisMonthLastDay;


		mDayList.clear();

		dayOfMonth = calendar.get(Calendar.DAY_OF_WEEK);
		thisMonthLastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

		calendar.add(Calendar.MONTH, -1);
		Log.e("", calendar.get(Calendar.DAY_OF_MONTH)+"");

		lastMonthStartDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

		calendar.add(Calendar.MONTH, 1);
		Log.e("", calendar.get(Calendar.DAY_OF_MONTH)+"");

		if(dayOfMonth == SUNDAY)
		{
			dayOfMonth += 7;
		}

		lastMonthStartDay -= (dayOfMonth-1)-1;

		mTvCalendarTitle.setText( (getStringMonth(mThisMonthCalendar.get(Calendar.MONTH) + 1)) + " "
				+ mThisMonthCalendar.get(Calendar.YEAR) );

		DayInfo day;

		Log.e("DayOfMOnth", dayOfMonth+"");

		for(int i=0; i<7; i++)
		{
			day = new DayInfo();
			day.setDay(dayText[i]);
			day.setInMonth(false);
			day.setToday(false);
			day.setIsText(true);
			mDayList.add(day);


		}
		for(int i=0; i<dayOfMonth-1; i++)
		{
			int date = lastMonthStartDay+i;
			day = new DayInfo();
			day.setDay(Integer.toString(date));
			day.setInMonth(false);
			day.setToday(false);
			day.setIsText(false);
			mDayList.add(day);
		}
		for(int i=1; i <= thisMonthLastDay; i++)
		{
			day = new DayInfo();
			day.setDay(Integer.toString(i));
			day.setInMonth(true);
			if(mThisMonthCalendar.get(Calendar.YEAR)==yearOfToday
					&& mThisMonthCalendar.get(Calendar.MONTH)==monthOfToday
					&& i==dayOfToday)
			{
				day.setToday(true);
			}
			else{
				day.setToday(false);
			}
			day.setIsText(false);

			mDayList.add(day);
		}
		for(int i=1; i<42-(thisMonthLastDay+dayOfMonth-1)+1; i++)
		{
			day = new DayInfo();
			day.setDay(Integer.toString(i));
			day.setInMonth(false);
			day.setToday(false);
			day.setIsText(false);
			mDayList.add(day);
		}

		initCalendarAdapter();
	}

	/**
	 * 
	 * @param calendar
	 * @return LastMonthCalendar
	 */
	private Calendar getLastMonth(Calendar calendar)
	{
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
		calendar.add(Calendar.MONTH, -1);
		mTvCalendarTitle.setText(mThisMonthCalendar.get(Calendar.YEAR) + "  "
				+ (getStringMonth(mThisMonthCalendar.get(Calendar.MONTH) + 1)));
		return calendar;
	}

	/**
	 *  Calendar 
	 * 
	 * @param calendar
	 * @return NextMonthCalendar
	 */
	private Calendar getNextMonth(Calendar calendar)
	{
		calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
		calendar.add(Calendar.MONTH, +1);
		mTvCalendarTitle.setText(mThisMonthCalendar.get(Calendar.YEAR) + "  "
				+ (getStringMonth(mThisMonthCalendar.get(Calendar.MONTH) + 1)));
		return calendar;
	}
	
	private Calendar getThisMonth(Calendar calendar)
	{
		calendar.set(yearOfToday,monthOfToday, 1);
		mTvCalendarTitle.setText(mThisMonthCalendar.get(Calendar.YEAR) + "  "
				+ (getStringMonth(mThisMonthCalendar.get(Calendar.MONTH) + 1)));
		return calendar;
	}


	@Override
	public void onItemClick(final AdapterView<?> parent, final View v, final int position, final long arg3)
	{
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
		final AlertDialog.Builder builder3 = new AlertDialog.Builder(this);

		final int selectedYear = mThisMonthCalendar.get(Calendar.YEAR);
		final int selectedMonth = mThisMonthCalendar.get(Calendar.MONTH) + 1;
		final String selectedDay = mDayList.get(position).getDay();

		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		final View layout = inflater.inflate(R.layout.addweight,(ViewGroup) findViewById(R.id.addweightdialog));

		if(mDayList.get(position).isInMonth()){

			builder.setTitle(getStringMonth(selectedMonth) + " " + selectedDay);
			builder.setMessage("Choose an action:");
			builder.setIcon(me.croute.calendarexample.R.drawable.eft);

			builder.setPositiveButton("View Day", new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub

					Intent gotoDayView = new Intent( getApplicationContext(), DayView.class );
					
					gotoDayView.putExtra( autoInstance.getPackageName() + ".day", Integer.parseInt( selectedDay ) );
					gotoDayView.putExtra( autoInstance.getPackageName() + ".month", selectedMonth);
					gotoDayView.putExtra( autoInstance.getPackageName() + ".year", selectedYear);					
					
					startActivity(gotoDayView);
				}
			});

			builder.setNeutralButton("Add Item", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					builder2.setTitle(getStringMonth(selectedMonth) + " " + selectedDay);
					builder2.setMessage("Choose an item to add:");
					builder2.setIcon(me.croute.calendarexample.R.drawable.eft);

					builder2.setPositiveButton("Workout", new DialogInterface.OnClickListener(){
						@Override
						public void onClick(DialogInterface dialog, int which) {

							onItemClick(parent,v,position,arg3);

							Intent addNewWorkout = new Intent(getApplicationContext(), AddWorkout.class);

							int year = selectedYear;
							int month = selectedMonth;
							int day = Integer.parseInt( selectedDay );
							
							long date = Controller.createDateLong(day, month, year);

							addNewWorkout.putExtra( "Date", date );
							startActivity(addNewWorkout);
							dialog.cancel();
							
						}
					});

					builder2.setNeutralButton("Weight", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							
							String weightStatus;
							double weight = controller.getWeightByDay( 
									Integer.parseInt( selectedDay ),
									selectedMonth,
									selectedYear );
							if (weight == 0.0 ){
								weightStatus = "No weight added";
							}
							else{
								weightStatus = weight + "lbs";
							}
							
							builder3.setTitle( getStringMonth(selectedMonth) + " " + selectedDay 
									+ "    " + weightStatus );
							builder3.setIcon(me.croute.calendarexample.R.drawable.eft);

							builder3.setMessage("Edit personal weight in pounds:");

							final EditText weightBox = new EditText(autoInstance);
							builder3.setView(weightBox);

							builder3.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
								@Override
								public void onClick(DialogInterface dialog, int which) {
									onItemClick(parent,v,position,arg3);
									
									dialog.cancel();
								}
							});
							
							builder3.setPositiveButton("Save", new DialogInterface.OnClickListener(){
								@Override
								public void onClick(DialogInterface dialog, int which) {
									onItemClick(parent,v,position,arg3);

									String textString = weightBox.getText().toString();
									textString = textString.trim();
									float weight = -1; 

									try{
										weight = Float.parseFloat( textString ); 
									}catch(Exception ex){}

									if ( weight > 0 && weight < 1000 ){

										/* round to one decimal place */
										String w = ( (Float) weight ).toString();

										int dot = w.indexOf( '.' );

										if( dot == -1){
											w = w + ".0";
										}
										else{
											w = w.substring(0, dot + 2);
										}
										
										int day = Integer.parseInt( selectedDay );
										int month = selectedMonth;
										int year =  selectedYear;
										
										controller.saveWeight( w, day, month, year);

										Context context = getApplicationContext();
										CharSequence text = "Weight Added";
										int duration = Toast.LENGTH_SHORT;

										Toast toast = Toast.makeText(context, text, duration);
										toast.show();
									}
									else{

										Context context = getApplicationContext();
										CharSequence text = "Invalid weight. Please enter a valid weight.";
										int duration = Toast.LENGTH_LONG;

										Toast toast = Toast.makeText(context, text, duration);
										toast.show();
									}
								}
							});
							builder3.show();
						}
					});
					builder2.show();
				}
			});
			builder.show();
		}
	}

	@Override
	public void onClick(View v)
	{
		switch(v.getId())
		{
		case R.id.gv_calendar_activity_b_last:
			mThisMonthCalendar = getLastMonth(mThisMonthCalendar);
			getCalendar(mThisMonthCalendar);
			break;
		case R.id.gv_calendar_activity_b_next:
			mThisMonthCalendar = getNextMonth(mThisMonthCalendar);
			getCalendar(mThisMonthCalendar);
			break;
		case R.id.gv_calendar_activity_return:
			mThisMonthCalendar = getThisMonth(mThisMonthCalendar);
			getCalendar(mThisMonthCalendar);
			break;
		case R.id.gv_calendar_activity_history:

			Intent gotoHistory = new Intent( getApplicationContext(), ExerciseHistory.class );
			startActivity(gotoHistory);

			break;
		}
	}

	private void initCalendarAdapter()
	{
		mCalendarAdapter = new CalendarAdapter(this, R.layout.day, mDayList);
		mGvCalendar.setAdapter(mCalendarAdapter);
	}
	private String getStringMonth(int m){
		if(m > 0 && m < 13){
			switch(m){
			case 1:
				return "January";
			case 2:
				return "February";
			case 3: 
				return "March";
			case 4:
				return "April";
			case 5: 
				return "May";
			case 6:
				return "June";
			case 7:
				return "July";
			case 8: 
				return "August";
			case 9:
				return "September";
			case 10:
				return "October";
			case 11:
				return "November";
			case 12:
				return "December";
			}

		}
		return null;


	}
}